package com.fenghuajueli.module_user.activity.userinfo;

import static com.fenghuajueli.module_user.activity.login.LoginActivity.KEY_APPLY_PRIVACY;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants;
import com.fenghuajueli.libbasecoreui.data.entity.user.ThirdLoginInfoEntity;
import com.fenghuajueli.libbasecoreui.data.entity.user.UserInfoEntity;
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.listener.OnBaseClick;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.R;
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity;
import com.fenghuajueli.module_user.databinding.ActivityUserInfoBinding;
import com.fenghuajueli.module_user.dialog.DeleteUserDialog;
import com.fenghuajueli.module_user.dialog.PickAvatarDialog;
import com.fenghuajueli.module_user.dialog.UserTipDialog;
import com.fenghuajueli.module_user.model.RequestInfoModel;
import com.fenghuajueli.module_user.model.UserViewModel;
import com.fenghuajueli.module_user.network.result.TemplateResult;
import com.fenghuajueli.module_user.network.model.template.ThemeColor;
import com.fenghuajueli.module_user.utils.FileUtils;
import com.fenghuajueli.module_user.utils.PermissionUtil;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;

@Route(path = UserModuleRoute.USER_INFO_ACTIVITY)
public class UserInfoActivity extends UserViewModelBaseActivity implements View.OnClickListener {

    ActivityUserInfoBinding binding;
    private final UserViewModel userViewModel = new UserViewModel();
    private DeleteUserDialog deleteUserDialog;

    private PickAvatarDialog pickAvatarDialog;

    //本地存储头像标识
    private final String LOCAL_AVATAR_KIND = "local_avatar_kind";

    @Override
    public BaseViewModel setBaseViewModel() {
        return userViewModel;
    }

    private PromptDialog promptDialog;
    private String dlstr = "您的个人信息已经保存在手机存储里。";

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    promptDialog.showLoading("保存中...");
                    break;

                case 2:
                    promptDialog.dismiss();
                    ToastUtils.showLong(dlstr);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUserInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EventBus.getDefault().register(this);
        binding.ivClose.setOnClickListener(v -> onBackPressed());
        promptDialog = new PromptDialog(this);

        initUserInfo();
        setOnClick();

        initPickAvatarDialog();
        updateViewsContent();
        userViewModel.userInfoGetSuccess.observe(this, userInfoEntity -> setUserInfo());
        userViewModel.templateResult.observe(this, result -> {
            if (result instanceof TemplateResult.Success){
                ThemeColor themeColor = ((TemplateResult.Success) result).getData().getTheme_color();
                binding.btnLoginOut.getBackground().setTint(Color.parseColor(themeColor.getTheme_colors()));
            }
        });
    }

    private void initPickAvatarDialog() {
        pickAvatarDialog = new PickAvatarDialog(this);
        pickAvatarDialog.setPicklistener(new OnBaseClick<String>() {
            @Override
            public void onClick(String s) {
                MmkvUtils.save(LOCAL_AVATAR_KIND,s);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateViewsContent();
                    }
                });
            }
        });
    }

    private void updateViewsContent() {
        //head
        String imgUrl = MmkvUtils.get(LOCAL_AVATAR_KIND,"");
        if (!imgUrl.isEmpty()){
            Glide.with(this).load(imgUrl).into(binding.actUserAvatarCiv);
        } else {
            Glide.with(this).load(R.mipmap.icon_default_avatar).into(binding.actUserAvatarCiv);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!SwitchKeyUtils.getPayStatus()) {
            binding.vipLevelContainer.setVisibility(View.GONE);
            binding.vipDayContainer.setVisibility(View.GONE);
            binding.rlVipContainer.setVisibility(View.GONE);
        } else {
            binding.vipLevelContainer.setVisibility(View.VISIBLE);
            binding.vipDayContainer.setVisibility(View.VISIBLE);
            binding.rlVipContainer.setVisibility(View.VISIBLE);
        }

    }

    private void initUserInfo() {
        if (UserInfoUtils.getInstance().isLogin()) {
            binding.btnLoginOut.setVisibility(View.VISIBLE);
            binding.btnDeleteUser.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(UserInfoUtils.getInstance().getUserInfoEntity().getToken())) {
                userViewModel.getUserInfo(this, UserInfoUtils.getInstance().getUserInfoEntity().getToken());
            } else {
                setUserInfo();
            }
        } else {
            binding.tvUserId.setText("");
            binding.tvShardId.setText(RequestInfoModel.visitorShareId);
            binding.tvVipLevel.setText("游客用户");
            binding.tvVipDay.setText("0天");
        }

        if (!MmkvUtils.get(RequestInfoModel.LOGIN_OUT, false)){
            binding.btnDeleteUser.setVisibility(View.GONE);
        }
    }

    private void setOnClick() {
        binding.tvOpenVip.setOnClickListener(this);
        binding.btnDeleteUser.setOnClickListener(this);
        binding.btnLoginOut.setOnClickListener(this);
        binding.tvInfoDownload.setOnClickListener(this);
        binding.actUserAvatarLl.setOnClickListener(this);
    }


    public void showVipLevel() {
        binding.tvVipLevel.setText(UserInfoUtils.getInstance().getVipNameByType());
        binding.tvVipDay.setText(UserInfoUtils.getInstance().getShowVipDaysByType());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.LOGIN_OUT) {
            finish();
        }
        if (eventBusEntity.getCode() == EventBusConstants.DELETE_USER) {
            UserTipDialog.show(this, R.mipmap.user_icon_success_01, "注销成功").setOnDismissListener(dialog -> finish());
        }
        if (eventBusEntity.getCode() == EventBusConstants.UPDATE_USER_INFO) {
            setUserInfo();
        }
    }

    @Override
    public void onClick(View view) {
        if (QuickClickUtils.isFastClick()) {
            return;
        }

        int viewId = view.getId();
        if (viewId == R.id.tvOpenVip) {
            ARouter.getInstance().build(UserModuleRoute.USER_OPEN_VIP_ACTIVITY).navigation();
        } else if (viewId == R.id.btnDeleteUser) {
            if (!UserInfoUtils.getInstance().isLogin()) {
                return;
            }
            showDeleteUserTipsDialog();
        } else if (viewId == R.id.btnLoginOut) {
            showLoadingDialog("正在退出登录...");
            binding.btnLoginOut.postDelayed(() -> {
                UserInfoUtils.getInstance().clearLoginInfo();
                hideLoadingDialog();
                MmkvUtils.save(RequestInfoModel.LOGIN_OUT, true);
                EventBus.getDefault().post(new EventEntity(EventBusConstants.LOGIN_OUT, null));
                MmkvUtils.save(KEY_APPLY_PRIVACY, false);
                finish();
            }, 1000);
        } else if (viewId == R.id.tvInfoDownload) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PermissionUtil.requestPermisions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, (allGranted, grantedList, deniedList) -> {
                    if (allGranted){
                        downloadUserinfo();
                    }
                });
            } else {
                downloadUserinfo();
            }
        } else if (viewId == R.id.act_user_avatar_ll){
            pickAvatarDialog.show();
        }
    }


    public void downloadUserinfo() {
        mHandler.sendEmptyMessage(1);
        String nickName = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getUser_name();
        String userid = "" + UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getUser_id();
        String vipLevel = UserInfoUtils.getInstance().getVipNameByType();
        String vipDays = UserInfoUtils.getInstance().getShowVipDaysByType();
        String userinfo;
        if (SwitchKeyUtils.getPayStatus()) {
            userinfo = "昵称：" + nickName + "\n" + "用户ID：" + userid + "\n" + "vip等级：" + vipLevel + "\n" + "vip剩余天数：" + vipDays + "\n";
        } else {
            userinfo = "昵称：" + nickName + "\n" + "用户ID：" + userid + "\n";
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            dlstr = "您的个人信息已经保存在手机存储里的Download文件夹。";
            FileUtils.saveTxt2Public(this, "个人信息副本.txt", userinfo, "Download");
        } else {
            dlstr = "您的个人信息已经保存在手机存储里。";
            FileUtils.writeTxtToFile(userinfo, FileUtils.getFilepath());
        }
        mHandler.sendEmptyMessageDelayed(2, 1000);
    }


    private void showDeleteUserTipsDialog() {
        deleteUserDialog = new DeleteUserDialog(this);
        deleteUserDialog.setOnButtonClickListener(new DeleteUserDialog.OnButtonClickListener() {
            @Override
            public void onLeftButtonClick() {
                if (UserInfoUtils.getInstance().isPhoneNum()) {
                    ARouter.getInstance().build(UserModuleRoute.USER_DELETE_ACCOUNT).navigation();
                } else {
                    List<ThirdLoginInfoEntity> list = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getLogin_list();
                    //因为目前只有微信登陆  所以只需判断是否有第三方账号的数据即可 阿里云一键登录是会读取手机号保存到手机号字段的
                    if (list != null && list.size() > 0) {
                        showWxLogOutDialog();
                    } else {
                        showToast("账号异常，请联系客服进行注销！");
                    }
                }
            }

            @Override
            public void onRightButtonClick() {

            }
        });
        deleteUserDialog.show();
    }


    /**
     * 微信的注销提示
     */
    private void showWxLogOutDialog() {

        deleteUserDialog = new DeleteUserDialog(this, "", "因您正在注销微信登录账号信息，需要再次验证您的微信身份信息，验证成功后将清除微信登录账号数据", "微信验证", "取消验证");
        deleteUserDialog.setOnButtonClickListener(new DeleteUserDialog.OnButtonClickListener() {
            @Override
            public void onLeftButtonClick() {
                //走第三方解绑的接口 当做注销账号
                MmkvUtils.save(KEY_APPLY_PRIVACY, false);
                userViewModel.verificationWxToLogOut(UserInfoActivity.this);
            }

            @Override
            public void onRightButtonClick() {

            }
        });
        deleteUserDialog.show();
    }

    private void setUserInfo() {
        if (UserInfoUtils.getInstance().isLogin()) {
            if (UserInfoUtils.getInstance().getUserInfoEntity() != null) {
                UserInfoEntity.UserInfoBean userInfo = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo();
                binding.tvUserId.setText(userInfo.getUser_id() + "");
                showVipLevel();
                if (SwitchKeyUtils.getPayStatus()) {
//                    if (UserInfoUtils.getInstance().isForeverVip()) {
//                        binding.tvOpenVip.setVisibility(View.GONE);
//                    } else {
//                        binding.tvOpenVip.setVisibility(View.VISIBLE);
//                    }
                    binding.vipDayContainer.setVisibility(View.VISIBLE);
                    binding.vipLevelContainer.setVisibility(View.VISIBLE);
                    binding.rlVipContainer.setVisibility(View.VISIBLE);
                } else {
                    binding.vipDayContainer.setVisibility(View.GONE);
                    binding.vipLevelContainer.setVisibility(View.GONE);
                    binding.rlVipContainer.setVisibility(View.GONE);
                }
                binding.tvShardId.setText(userInfo.getShare_id());
            }
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}